#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //连接信号与槽
    connect(ui->newaction,&QAction::triggered,this,&MainWindow::newactionslot);
    connect(ui->openaction,&QAction::triggered,this,&MainWindow::openactionslot);
    connect(ui->saveaction,&QAction::triggered,this,&MainWindow::saveactionslot);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::newactionslot()
{
    ui->textEdit->clear();
    this->setWindowTitle("新建文本文档.txt");
}

//打开文件
void MainWindow::openactionslot()
{
    QString filename=QFileDialog::getOpenFileName(this, "选择一个文件",
                                 QCoreApplication::applicationFilePath(),"*.cpp");
    if(filename.isEmpty())
        QMessageBox::warning(this,"警告","请选择一个文件");
    else
    {
        QFile file(filename);
        file.open(QIODevice::ReadOnly);
        QByteArray ba = file.readAll();
        ui->textEdit->setText(QString(ba));
        //qDebug()<<filename;
    }
}
//保存文件
void MainWindow::saveactionslot()
{
    QString filename=QFileDialog::getSaveFileName(this, "选择一个文件",
                                 QCoreApplication::applicationFilePath());
    if(filename.isEmpty())
        QMessageBox::warning(this,"警告","请选择一个文件");
    else
    {
        QFile file(filename);
        file.open(QIODevice::WriteOnly);
        //ui->textEdit->toPlainText();//读出内容

        QByteArray ba;
        ba.append(ui->textEdit->toPlainText());
        file.write(ba);
        file.close();
    }
}
//Ctrl+S
void MainWindow::keyPressEvent(QKeyEvent *k)
{
   if(k->modifiers()==Qt::ControlModifier && k->key()==Qt::Key_S)
   {
      saveactionslot();
   }
}
//鼠标
void MainWindow::mousePressEvent(QMouseEvent *m)
{
    QPoint pt=m->pos();
    qDebug()<<pt;

    if(m->button() == Qt::LeftButton)
    {
        qDebug()<<"左键被按下";
    }
    else if(m->button() == Qt::RightButton)
    {
        qDebug()<<"右键被按下";
    }
}
